<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户中心 - 外卖平台</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: #f5f5f5;
            color: #333;
        }
        
        .header {
            background: white;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            padding: 20px 0;
            margin-bottom: 30px;
        }
        
        .header-content {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .header h1 {
            color: #ff6b6b;
            font-size: 28px;
        }
        
        .user-info {
            display: flex;
            align-items: center;
            gap: 15px;
        }
        
        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-weight: 500;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-block;
        }
        
        .btn-primary {
            background: #ff6b6b;
            color: white;
        }
        
        .btn-primary:hover {
            background: #ee5a24;
            transform: translateY(-2px);
        }
        
        .btn-secondary {
            background: #6c757d;
            color: white;
        }
        
        .btn-secondary:hover {
            background: #5a6268;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 20px;
        }
        
        .tabs {
            display: flex;
            background: white;
            border-radius: 12px;
            padding: 4px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .tab {
            flex: 1;
            padding: 15px;
            border: none;
            background: transparent;
            cursor: pointer;
            font-size: 16px;
            font-weight: 600;
            color: #666;
            border-radius: 8px;
            transition: all 0.3s ease;
        }
        
        .tab.active {
            background: #ff6b6b;
            color: white;
            box-shadow: 0 2px 10px rgba(255, 107, 107, 0.3);
        }
        
        .tab-content {
            display: none;
        }
        
        .tab-content.active {
            display: block;
        }
        
        .merchants-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
            gap: 20px;
            margin-top: 20px;
        }
        
        .merchant-card {
            background: white;
            border-radius: 12px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            transition: all 0.3s ease;
            cursor: pointer;
        }
        
        .merchant-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 5px 20px rgba(0,0,0,0.15);
        }
        
        .merchant-image {
            width: 100%;
            height: 200px;
            border-radius: 8px;
            overflow: hidden;
            margin-bottom: 15px;
        }
        
        .merchant-image img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        
        .merchant-info h3 {
            color: #333;
            margin-bottom: 10px;
            font-size: 20px;
        }
        
        .merchant-rating {
            display: flex;
            align-items: center;
            gap: 5px;
            margin-bottom: 10px;
        }
        
        .merchant-rating .stars {
            color: #ffc107;
        }
        
        .merchant-rating .rating {
            color: #666;
            font-size: 14px;
        }
        
        .merchant-details {
            color: #666;
            font-size: 14px;
            margin-bottom: 15px;
        }
        
        .merchant-details p {
            margin-bottom: 5px;
        }
        
        .merchant-tags {
            display: flex;
            gap: 5px;
            flex-wrap: wrap;
            margin-bottom: 15px;
        }
        
        .tag {
            background: #f8f9fa;
            color: #666;
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 12px;
        }
        
        .dishes-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 20px;
            margin-top: 20px;
        }
        
        .dish-card {
            background: white;
            border-radius: 12px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            transition: all 0.3s ease;
        }
        
        .dish-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 5px 20px rgba(0,0,0,0.15);
        }
        
        .dish-image {
            width: 100%;
            height: 200px;
            border-radius: 8px;
            overflow: hidden;
            margin-bottom: 15px;
        }
        
        .dish-image img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        
        .dish-info h3 {
            color: #333;
            margin-bottom: 10px;
            font-size: 18px;
        }
        
        .dish-price {
            color: #ff6b6b;
            font-size: 20px;
            font-weight: bold;
            margin-bottom: 10px;
        }
        
        .dish-category {
            background: #f8f9fa;
            color: #666;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            display: inline-block;
            margin-bottom: 10px;
        }
        
        .dish-description {
            color: #666;
            font-size: 14px;
            line-height: 1.5;
            margin-bottom: 15px;
        }
        
        .dish-actions {
            display: flex;
            gap: 10px;
        }
        
        .add-to-cart-btn {
            background: #28a745;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
        }
        
        .orders-list {
            background: white;
            border-radius: 12px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .order-card {
            border: 1px solid #e9ecef;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 15px;
            transition: all 0.3s ease;
        }
        
        .order-card:hover {
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .order-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }
        
        .order-id {
            font-weight: bold;
            color: #333;
        }
        
        .order-status {
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
        }
        
        .status-pending {
            background: #fff3cd;
            color: #856404;
        }
        
        .status-preparing {
            background: #d1ecf1;
            color: #0c5460;
        }
        
        .status-ready {
            background: #d4edda;
            color: #155724;
        }
        
        .status-delivering {
            background: #cce5ff;
            color: #004085;
        }
        
        .status-completed {
            background: #e2e3e5;
            color: #383d41;
        }
        
        .order-content {
            margin-bottom: 15px;
        }
        
        .order-content p {
            margin-bottom: 5px;
            color: #666;
        }
        
        .back-btn {
            position: fixed;
            top: 20px;
            left: 20px;
            background: rgba(255, 107, 107, 0.8);
            border: none;
            border-radius: 50%;
            width: 50px;
            height: 50px;
            cursor: pointer;
            color: white;
            font-size: 20px;
            transition: all 0.3s ease;
            z-index: 1000;
        }
        
        .back-btn:hover {
            background: #ff6b6b;
            transform: scale(1.1);
        }
        
        .hidden {
            display: none;
        }
        
        .message {
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 20px;
            font-weight: 500;
            text-align: center;
        }
        
        .message.success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .message.error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
    </style>
</head>
<body>
    <button class="back-btn" onclick="goBack()">←</button>
    
    <div class="header">
        <div class="header-content">
            <h1>👤 用户中心</h1>
            <div class="user-info">
                <span id="userName">用户名</span>
                <button class="btn btn-secondary" onclick="logout()">退出登录</button>
            </div>
        </div>
    </div>
    
    <div class="container">
        <div id="message"></div>
        
        <div class="tabs">
            <button class="tab active" onclick="showTab('merchants')">🏪 浏览商家</button>
            <button class="tab" onclick="showTab('dishes')">🍽️ 菜品推荐</button>
            <button class="tab" onclick="showTab('cart')">🛒 购物车</button>
            <button class="tab" onclick="showTab('orders')">📋 我的订单</button>
            <button class="tab" onclick="showTab('profile')">👤 个人资料</button>
        </div>
        
        <!-- 浏览商家 -->
        <div id="merchants" class="tab-content active">
            <h2>附近商家</h2>
            <div class="merchants-grid" id="merchantsGrid">
                <!-- 商家将通过JavaScript动态加载 -->
            </div>
        </div>
        
        <!-- 菜品推荐 -->
        <div id="dishes" class="tab-content">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                <h2>🤖 AI智能推荐</h2>
                <div style="display: flex; gap: 10px;">
                    <button class="btn btn-primary" onclick="refreshAIRecommendations()" style="padding: 8px 16px; font-size: 14px;">
                        🔄 刷新推荐
                    </button>
                    <button class="btn btn-secondary" onclick="showRecommendationSettings()" style="padding: 8px 16px; font-size: 14px;">
                        ⚙️ 推荐设置
                    </button>
                </div>
            </div>
            
            <!-- 推荐上下文信息 -->
            <div id="recommendationContext" style="
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                color: white;
                padding: 20px;
                border-radius: 12px;
                margin-bottom: 20px;
                display: none;
            ">
                <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px;">
                    <div style="text-align: center;">
                        <div style="font-size: 24px; margin-bottom: 5px;" id="timeIcon">🌅</div>
                        <div style="font-size: 14px; opacity: 0.9;" id="timeInfo">上午 09:30</div>
                    </div>
                    <div style="text-align: center;">
                        <div style="font-size: 24px; margin-bottom: 5px;" id="weatherIcon">☀️</div>
                        <div style="font-size: 14px; opacity: 0.9;" id="weatherInfo">阳光明媚 25°C</div>
                    </div>
                    <div style="text-align: center;">
                        <div style="font-size: 24px; margin-bottom: 5px;" id="seasonIcon">🌸</div>
                        <div style="font-size: 14px; opacity: 0.9;" id="seasonInfo">春季推荐</div>
                    </div>
                    <div style="text-align: center;">
                        <div style="font-size: 24px; margin-bottom: 5px;" id="preferenceIcon">❤️</div>
                        <div style="font-size: 14px; opacity: 0.9;" id="preferenceInfo">基于您的偏好</div>
                    </div>
                </div>
            </div>
            
            <!-- 推荐菜品网格 -->
            <div class="dishes-grid" id="dishesGrid">
                <!-- 菜品将通过JavaScript动态加载 -->
            </div>
            
            <!-- 推荐设置模态框 -->
            <div id="recommendationSettingsModal" style="
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(0,0,0,0.5);
                z-index: 1000;
                display: none;
                align-items: center;
                justify-content: center;
                padding: 20px;
            ">
                <div style="
                    background: white;
                    border-radius: 12px;
                    max-width: 500px;
                    width: 100%;
                    max-height: 80vh;
                    overflow-y: auto;
                    position: relative;
                ">
                    <div style="
                        position: sticky;
                        top: 0;
                        background: white;
                        padding: 20px;
                        border-bottom: 1px solid #eee;
                        display: flex;
                        justify-content: space-between;
                        align-items: center;
                    ">
                        <h3>推荐设置</h3>
                        <button onclick="closeRecommendationSettings()" style="
                            background: #dc3545;
                            color: white;
                            border: none;
                            border-radius: 50%;
                            width: 30px;
                            height: 30px;
                            cursor: pointer;
                        ">×</button>
                    </div>
                    <div style="padding: 20px;">
                        <div style="margin-bottom: 20px;">
                            <label style="display: block; margin-bottom: 10px; font-weight: 600;">推荐数量</label>
                            <input type="range" id="recommendationCount" min="5" max="20" value="10" style="width: 100%;">
                            <div style="text-align: center; margin-top: 5px; color: #666;">
                                <span id="countValue">10</span> 个推荐
                            </div>
                        </div>
                        
                        <div style="margin-bottom: 20px;">
                            <label style="display: block; margin-bottom: 10px; font-weight: 600;">口味偏好</label>
                            <div style="display: flex; gap: 10px; flex-wrap: wrap;">
                                <label style="display: flex; align-items: center; cursor: pointer;">
                                    <input type="checkbox" id="prefSpicy" style="margin-right: 5px;">
                                    <span>🌶️ 辣味</span>
                                </label>
                                <label style="display: flex; align-items: center; cursor: pointer;">
                                    <input type="checkbox" id="prefSweet" style="margin-right: 5px;">
                                    <span>🍯 甜味</span>
                                </label>
                                <label style="display: flex; align-items: center; cursor: pointer;">
                                    <input type="checkbox" id="prefSour" style="margin-right: 5px;">
                                    <span>🍋 酸味</span>
                                </label>
                                <label style="display: flex; align-items: center; cursor: pointer;">
                                    <input type="checkbox" id="prefHealthy" style="margin-right: 5px;">
                                    <span>🥗 健康</span>
                                </label>
                            </div>
                        </div>
                        
                        <div style="margin-bottom: 20px;">
                            <label style="display: block; margin-bottom: 10px; font-weight: 600;">价格范围</label>
                            <div style="display: flex; gap: 10px; align-items: center;">
                                <input type="number" id="priceMin" placeholder="最低价格" style="flex: 1; padding: 8px; border: 1px solid #ddd; border-radius: 4px;">
                                <span>-</span>
                                <input type="number" id="priceMax" placeholder="最高价格" style="flex: 1; padding: 8px; border: 1px solid #ddd; border-radius: 4px;">
                            </div>
                        </div>
                        
                        <div style="display: flex; gap: 10px;">
                            <button class="btn btn-primary" onclick="saveRecommendationSettings()" style="flex: 1;">保存设置</button>
                            <button class="btn btn-secondary" onclick="resetRecommendationSettings()" style="flex: 1;">重置</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 我的订单 -->
        <div id="orders" class="tab-content">
            <h2>我的订单</h2>
            <div class="orders-list" id="ordersList">
                <!-- 订单将通过JavaScript动态加载 -->
            </div>
        </div>
        
        <!-- 购物车 -->
        <div id="cart" class="tab-content">
            <h2>购物车</h2>
            <div id="cartContent" style="background: white; border-radius: 12px; padding: 20px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
                <!-- 购物车内容将通过JavaScript动态加载 -->
            </div>
        </div>
        
        <!-- 个人资料 -->
        <div id="profile" class="tab-content">
            <h2>个人资料</h2>
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
                <!-- 左侧：基本信息 -->
                <div style="background: white; border-radius: 12px; padding: 25px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
                    <div style="display: flex; align-items: center; margin-bottom: 25px;">
                        <div style="
                            width: 80px;
                            height: 80px;
                            border-radius: 50%;
                            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                            display: flex;
                            align-items: center;
                            justify-content: center;
                            color: white;
                            font-size: 32px;
                            font-weight: bold;
                            margin-right: 20px;
                        " id="userAvatar">
                            ${currentUser ? (currentUser.name || currentUser.username || 'U').charAt(0).toUpperCase() : 'U'}
                        </div>
                        <div>
                            <h3 style="margin: 0 0 5px 0; color: #333;" id="userDisplayName">用户</h3>
                            <p style="margin: 0; color: #666; font-size: 14px;">会员等级: 普通会员</p>
                        </div>
                    </div>
                    
                <div class="profile-section">
                        <h3 style="color: #333; margin-bottom: 20px; display: flex; align-items: center;">
                            <span style="margin-right: 10px;">👤</span>基本信息
                        </h3>
                        <div class="form-group" style="margin-bottom: 15px;">
                            <label style="display: block; margin-bottom: 5px; color: #666; font-weight: 500;">用户名</label>
                            <input type="text" id="profileUsername" value="" style="
                                width: 100%;
                                padding: 12px;
                                border: 1px solid #ddd;
                                border-radius: 8px;
                                font-size: 14px;
                            ">
                    </div>
                        <div class="form-group" style="margin-bottom: 15px;">
                            <label style="display: block; margin-bottom: 5px; color: #666; font-weight: 500;">手机号</label>
                            <input type="text" id="profilePhone" value="" style="
                                width: 100%;
                                padding: 12px;
                                border: 1px solid #ddd;
                                border-radius: 8px;
                                font-size: 14px;
                            ">
                    </div>
                        <div class="form-group" style="margin-bottom: 20px;">
                            <label style="display: block; margin-bottom: 5px; color: #666; font-weight: 500;">邮箱</label>
                            <input type="email" id="profileEmail" value="" style="
                                width: 100%;
                                padding: 12px;
                                border: 1px solid #ddd;
                                border-radius: 8px;
                                font-size: 14px;
                            ">
                    </div>
                        <button class="btn btn-primary" onclick="updateProfile()" style="width: 100%; padding: 12px;">保存修改</button>
                    </div>
                </div>
                
                <!-- 右侧：统计信息和设置 -->
                <div style="display: flex; flex-direction: column; gap: 20px;">
                    <!-- 用户统计 -->
                    <div style="background: white; border-radius: 12px; padding: 25px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
                        <h3 style="color: #333; margin-bottom: 20px; display: flex; align-items: center;">
                            <span style="margin-right: 10px;">📊</span>我的统计
                        </h3>
                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                            <div style="text-align: center; padding: 15px; background: #f8f9fa; border-radius: 8px;">
                                <div style="font-size: 24px; font-weight: bold; color: #ff6b6b;" id="totalOrders">0</div>
                                <div style="color: #666; font-size: 12px;">总订单数</div>
                            </div>
                            <div style="text-align: center; padding: 15px; background: #f8f9fa; border-radius: 8px;">
                                <div style="font-size: 24px; font-weight: bold; color: #28a745;" id="totalSpent">¥0</div>
                                <div style="color: #666; font-size: 12px;">总消费</div>
                            </div>
                            <div style="text-align: center; padding: 15px; background: #f8f9fa; border-radius: 8px;">
                                <div style="font-size: 24px; font-weight: bold; color: #ffc107;" id="userRating">4.5</div>
                                <div style="color: #666; font-size: 12px;">平均评分</div>
                            </div>
                            <div style="text-align: center; padding: 15px; background: #f8f9fa; border-radius: 8px;">
                                <div style="font-size: 24px; font-weight: bold; color: #17a2b8;" id="memberDays">30</div>
                                <div style="color: #666; font-size: 12px;">会员天数</div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 偏好设置 -->
                    <div style="background: white; border-radius: 12px; padding: 25px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
                        <h3 style="color: #333; margin-bottom: 20px; display: flex; align-items: center;">
                            <span style="margin-right: 10px;">⚙️</span>偏好设置
                        </h3>
                        <div style="margin-bottom: 15px;">
                            <label style="display: flex; align-items: center; cursor: pointer;">
                                <input type="checkbox" id="notifications" style="margin-right: 10px;">
                                <span style="color: #666;">接收订单通知</span>
                            </label>
                        </div>
                        <div style="margin-bottom: 15px;">
                            <label style="display: flex; align-items: center; cursor: pointer;">
                                <input type="checkbox" id="promotions" style="margin-right: 10px;">
                                <span style="color: #666;">接收促销信息</span>
                            </label>
                        </div>
                        <div style="margin-bottom: 20px;">
                            <label style="display: flex; align-items: center; cursor: pointer;">
                                <input type="checkbox" id="location" style="margin-right: 10px;">
                                <span style="color: #666;">允许位置服务</span>
                            </label>
                        </div>
                        <button class="btn btn-secondary" onclick="savePreferences()" style="width: 100%; padding: 10px;">保存设置</button>
                    </div>
                </div>
            </div>
            
            <!-- 收货地址管理 -->
            <div style="background: white; border-radius: 12px; padding: 25px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); margin-top: 20px;">
                <h3 style="color: #333; margin-bottom: 20px; display: flex; align-items: center; justify-content: space-between;">
                    <span style="display: flex; align-items: center;">
                        <span style="margin-right: 10px;">📍</span>收货地址
                    </span>
                    <button class="btn btn-primary" onclick="addAddress()" style="padding: 8px 16px; font-size: 14px;">+ 添加新地址</button>
                </h3>
                    <div id="addressList">
                        <!-- 地址列表 -->
                    </div>
            </div>
            
            <!-- 最近订单 -->
            <div style="background: white; border-radius: 12px; padding: 25px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); margin-top: 20px;">
                <h3 style="color: #333; margin-bottom: 20px; display: flex; align-items: center; justify-content: space-between;">
                    <span style="display: flex; align-items: center;">
                        <span style="margin-right: 10px;">📋</span>最近订单
                    </span>
                    <button class="btn btn-secondary" onclick="showTab('orders')" style="padding: 8px 16px; font-size: 14px;">查看全部</button>
                </h3>
                <div id="recentOrders">
                    <!-- 最近订单列表 -->
                </div>
            </div>
        </div>
    </div>

    <script src="database.js"></script>
    <script src="ai-recommendation-engine.js"></script>
    <script>
        let currentUser = null;
        
        // 页面加载时初始化
        window.onload = function() {
            checkLoginStatus();
            loadMerchants();
            loadDishes();
            loadOrders();
            updateCartDisplay();
            loadProfile();
            loadAddresses();
        };
        
        function loadProfile() {
            if (currentUser) {
                document.getElementById('profileUsername').value = currentUser.username || '';
                document.getElementById('profilePhone').value = currentUser.phone || '';
                document.getElementById('profileEmail').value = currentUser.email || '';
                
                // 更新用户头像和显示名称
                const userAvatar = document.getElementById('userAvatar');
                const userDisplayName = document.getElementById('userDisplayName');
                if (userAvatar) {
                    userAvatar.textContent = (currentUser.name || currentUser.username || 'U').charAt(0).toUpperCase();
                }
                if (userDisplayName) {
                    userDisplayName.textContent = currentUser.name || currentUser.username || '用户';
                }
                
                // 加载用户统计信息
                loadUserStats();
                
                // 加载最近订单
                loadRecentOrders();
                
                // 加载偏好设置
                loadUserPreferences();
            }
        }
        
        function loadUserStats() {
            if (!currentUser) return;
            
            const orders = db.getOrdersByUser(currentUser.id);
            const totalOrders = orders.length;
            const totalSpent = orders.reduce((sum, order) => sum + order.finalPrice, 0);
            const memberDays = Math.floor((new Date() - new Date(currentUser.registerTime || Date.now())) / (1000 * 60 * 60 * 24));
            
            document.getElementById('totalOrders').textContent = totalOrders;
            document.getElementById('totalSpent').textContent = `¥${totalSpent.toFixed(2)}`;
            document.getElementById('memberDays').textContent = memberDays;
        }
        
        function loadRecentOrders() {
            if (!currentUser) return;
            
            const orders = db.getOrdersByUser(currentUser.id).slice(0, 3); // 只显示最近3个订单
            const recentOrdersDiv = document.getElementById('recentOrders');
            
            if (orders.length === 0) {
                recentOrdersDiv.innerHTML = `
                    <div style="text-align: center; padding: 20px; color: #666;">
                        <p>暂无订单记录</p>
                    </div>
                `;
                return;
            }
            
            recentOrdersDiv.innerHTML = orders.map(order => `
                <div style="
                    border: 1px solid #eee;
                    border-radius: 8px;
                    padding: 15px;
                    margin-bottom: 10px;
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                ">
                    <div>
                        <div style="font-weight: bold; color: #333;">订单 #${order.id}</div>
                        <div style="color: #666; font-size: 14px;">${order.dishes.map(dish => dish.name).join(', ')}</div>
                        <div style="color: #ff6b6b; font-weight: bold;">¥${order.finalPrice}</div>
                    </div>
                    <div style="text-align: right;">
                        <div style="
                            background: ${getStatusColor(order.status)};
                            color: white;
                            padding: 4px 8px;
                            border-radius: 12px;
                            font-size: 12px;
                            margin-bottom: 5px;
                        ">${getStatusText(order.status)}</div>
                        <div style="color: #666; font-size: 12px;">${order.orderTime}</div>
                    </div>
                </div>
            `).join('');
        }
        
        function loadUserPreferences() {
            if (!currentUser) return;
            
            const preferences = currentUser.preferences || {
                notifications: true,
                promotions: true,
                location: false
            };
            
            document.getElementById('notifications').checked = preferences.notifications;
            document.getElementById('promotions').checked = preferences.promotions;
            document.getElementById('location').checked = preferences.location;
        }
        
        function savePreferences() {
            if (!currentUser) return;
            
            const preferences = {
                notifications: document.getElementById('notifications').checked,
                promotions: document.getElementById('promotions').checked,
                location: document.getElementById('location').checked
            };
            
            currentUser.preferences = preferences;
            db.updateUser(currentUser.id, { preferences: preferences });
            localStorage.setItem('currentUser', JSON.stringify(currentUser));
            
            showMessage('偏好设置保存成功！', 'success');
        }
        
        function getStatusColor(status) {
            const colors = {
                'pending': '#ffc107',
                'preparing': '#17a2b8',
                'ready': '#28a745',
                'delivering': '#007bff',
                'completed': '#6c757d'
            };
            return colors[status] || '#6c757d';
        }
        
        function checkLoginStatus() {
            const savedUser = localStorage.getItem('currentUser');
            if (savedUser) {
                currentUser = JSON.parse(savedUser);
                if (currentUser.type !== 'user') {
                    alert('您没有权限访问用户中心！');
                    window.location.href = 'home.html';
                    return;
                }
                document.getElementById('userName').textContent = currentUser.name;
            } else {
                alert('请先登录！');
                window.location.href = 'login.html';
            }
        }
        
        function showTab(tabName) {
            // 隐藏所有标签页内容
            document.querySelectorAll('.tab-content').forEach(content => {
                content.classList.remove('active');
            });
            
            // 移除所有标签页的激活状态
            document.querySelectorAll('.tab').forEach(tab => {
                tab.classList.remove('active');
            });
            
            // 显示选中的标签页
            document.getElementById(tabName).classList.add('active');
            
            // 激活对应的标签按钮
            event.target.classList.add('active');
            
            // 根据标签页加载相应数据
            switch(tabName) {
                case 'merchants':
                    loadMerchants();
                    break;
                case 'dishes':
                    loadDishes();
                    break;
                case 'orders':
                    loadOrders();
                    break;
            }
        }
        
        function loadMerchants() {
            const merchants = db.getMerchants();
            const merchantsGrid = document.getElementById('merchantsGrid');
            
            if (merchants.length === 0) {
                merchantsGrid.innerHTML = `
                    <div style="grid-column: 1 / -1; text-align: center; padding: 40px; color: #666;">
                        <p>暂无商家</p>
                    </div>
                `;
                return;
            }
            
            merchantsGrid.innerHTML = merchants.map(merchant => `
                <div class="merchant-card" onclick="viewMerchant(${merchant.id})">
                    <div class="merchant-image">
                        <img src="${merchant.image}" alt="${merchant.name}" onerror="this.src='https://via.placeholder.com/350x200?text=商家图片'">
                    </div>
                    <div class="merchant-info">
                        <h3>${merchant.name}</h3>
                        <div class="merchant-rating">
                            <span class="stars">⭐⭐⭐⭐⭐</span>
                            <span class="rating">${merchant.rating}</span>
                        </div>
                        <div class="merchant-details">
                            <p>${merchant.description}</p>
                            <p>配送时间: ${merchant.deliveryTime}</p>
                            <p>配送费: ¥${merchant.deliveryFee}</p>
                            <p>起送价: ¥${merchant.minOrder}</p>
                        </div>
                        <div class="merchant-tags">
                            ${merchant.tags.map(tag => `<span class="tag">${tag}</span>`).join('')}
                        </div>
                    </div>
                </div>
            `).join('');
        }
        
        async function loadDishes() {
            if (!currentUser) return;
            
            const dishesGrid = document.getElementById('dishesGrid');
            const contextDiv = document.getElementById('recommendationContext');
            
            // 显示加载状态
            dishesGrid.innerHTML = `
                <div style="grid-column: 1 / -1; text-align: center; padding: 40px; color: #666;">
                    <div style="font-size: 24px; margin-bottom: 10px;">🤖</div>
                    <p>AI正在为您分析推荐...</p>
                </div>
            `;
            
            try {
                // 获取AI推荐
                const recommendationResult = await aiRecommendationEngine.generateRecommendations(currentUser.id, 10);
                const recommendations = recommendationResult.recommendations;
                const context = recommendationResult.context;
                
                if (recommendations.length === 0) {
                    dishesGrid.innerHTML = `
                        <div style="grid-column: 1 / -1; text-align: center; padding: 40px; color: #666;">
                            <p>暂无推荐菜品</p>
                        </div>
                    `;
                    return;
                }
                
                // 显示推荐上下文信息
                if (context) {
                    updateRecommendationContext(context);
                    contextDiv.style.display = 'block';
                }
                
                // 显示推荐菜品
                dishesGrid.innerHTML = recommendations.map(dish => `
                    <div class="dish-card" style="position: relative;">
                        <div class="dish-image">
                            <img src="${dish.image}" alt="${dish.name}" onerror="this.src='https://via.placeholder.com/300x200?text=菜品图片'">
                            <div style="
                                position: absolute;
                                top: 10px;
                                right: 10px;
                                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                                color: white;
                                padding: 4px 8px;
                                border-radius: 12px;
                                font-size: 12px;
                                font-weight: bold;
                            ">
                                AI推荐 ${Math.round(dish.recommendationScore)}分
                            </div>
                        </div>
                        <div class="dish-info">
                            <h3>${dish.name}</h3>
                            <div class="dish-price">¥${dish.price}</div>
                            <div class="dish-category">${dish.category}</div>
                            <div class="dish-description">${dish.description}</div>
                            
                            <!-- 推荐理由 -->
                            <div style="
                                background: #f8f9fa;
                                padding: 8px;
                                border-radius: 6px;
                                margin: 10px 0;
                                font-size: 12px;
                                color: #666;
                                border-left: 3px solid #667eea;
                            ">
                                <strong>推荐理由：</strong>${dish.recommendationReason}
                            </div>
                            
                            <div style="margin-bottom: 15px;">
                                <span style="color: #666; font-size: 12px;">评分: ${dish.rating} ⭐</span>
                                <span style="color: #666; font-size: 12px; margin-left: 10px;">销量: ${dish.sales}</span>
                                <span style="color: #667eea; font-size: 12px; margin-left: 10px;">推荐度: ${Math.round(dish.recommendationScore)}</span>
                            </div>
                            <div class="dish-actions">
                                <button class="add-to-cart-btn" onclick="addToCart(${dish.id})">加入购物车</button>
                                <button class="btn btn-secondary" onclick="showDishDetails(${dish.id})" style="margin-left: 10px; padding: 8px 12px; font-size: 12px;">详情</button>
                            </div>
                        </div>
                    </div>
                `).join('');
                
            } catch (error) {
                console.error('AI推荐失败:', error);
                dishesGrid.innerHTML = `
                    <div style="grid-column: 1 / -1; text-align: center; padding: 40px; color: #666;">
                        <p>AI推荐暂时不可用，正在加载普通菜品...</p>
                    </div>
                `;
                
                // 降级到普通菜品显示
                setTimeout(() => {
                    loadDishesFallback();
                }, 1000);
            }
        }
        
        // 降级方案：显示普通菜品
        function loadDishesFallback() {
            const dishes = db.getDishes();
            const dishesGrid = document.getElementById('dishesGrid');
            
            if (dishes.length === 0) {
                dishesGrid.innerHTML = `
                    <div style="grid-column: 1 / -1; text-align: center; padding: 40px; color: #666;">
                        <p>暂无菜品</p>
                    </div>
                `;
                return;
            }
            
            dishesGrid.innerHTML = dishes.slice(0, 10).map(dish => `
                <div class="dish-card">
                    <div class="dish-image">
                        <img src="${dish.image}" alt="${dish.name}" onerror="this.src='https://via.placeholder.com/300x200?text=菜品图片'">
                    </div>
                    <div class="dish-info">
                        <h3>${dish.name}</h3>
                        <div class="dish-price">¥${dish.price}</div>
                        <div class="dish-category">${dish.category}</div>
                        <div class="dish-description">${dish.description}</div>
                        <div style="margin-bottom: 15px;">
                            <span style="color: #666; font-size: 12px;">评分: ${dish.rating} ⭐</span>
                            <span style="color: #666; font-size: 12px; margin-left: 10px;">销量: ${dish.sales}</span>
                        </div>
                        <div class="dish-actions">
                            <button class="add-to-cart-btn" onclick="addToCart(${dish.id})">加入购物车</button>
                        </div>
                    </div>
                </div>
            `).join('');
        }
        
        // 更新推荐上下文信息
        function updateRecommendationContext(context) {
            const { timeInfo, weatherInfo } = context;
            
            // 时间信息
            const timeIcon = document.getElementById('timeIcon');
            const timeInfoText = document.getElementById('timeInfo');
            const timeIcons = {
                'morning': '🌅',
                'lunch': '☀️',
                'afternoon': '🌤️',
                'dinner': '🌆',
                'night': '🌙'
            };
            timeIcon.textContent = timeIcons[timeInfo.timeOfDay] || '🕐';
            timeInfoText.textContent = `${timeInfo.timeOfDay === 'morning' ? '上午' : 
                timeInfo.timeOfDay === 'lunch' ? '午餐' : 
                timeInfo.timeOfDay === 'afternoon' ? '下午' : 
                timeInfo.timeOfDay === 'dinner' ? '晚餐' : '夜间'} ${new Date().toLocaleTimeString('zh-CN', {hour: '2-digit', minute: '2-digit'})}`;
            
            // 天气信息
            const weatherIcon = document.getElementById('weatherIcon');
            const weatherInfoText = document.getElementById('weatherInfo');
            const weatherIcons = {
                'sunny': '☀️',
                'rainy': '🌧️',
                'cloudy': '☁️',
                'snowy': '❄️',
                'hot': '🔥'
            };
            weatherIcon.textContent = weatherIcons[weatherInfo.condition] || '🌤️';
            weatherInfoText.textContent = `${weatherInfo.description} ${weatherInfo.temperature}°C`;
            
            // 季节信息
            const seasonIcon = document.getElementById('seasonIcon');
            const seasonInfo = document.getElementById('seasonInfo');
            const seasonIcons = {
                'spring': '🌸',
                'summer': '☀️',
                'autumn': '🍂',
                'winter': '❄️'
            };
            seasonIcon.textContent = seasonIcons[timeInfo.season] || '🌱';
            seasonInfo.textContent = `${timeInfo.season === 'spring' ? '春季' : 
                timeInfo.season === 'summer' ? '夏季' : 
                timeInfo.season === 'autumn' ? '秋季' : '冬季'}推荐`;
            
            // 偏好信息
            const preferenceIcon = document.getElementById('preferenceIcon');
            const preferenceInfo = document.getElementById('preferenceInfo');
            preferenceIcon.textContent = '❤️';
            preferenceInfo.textContent = '基于您的偏好';
        }
        
        function loadOrders() {
            if (!currentUser) return;
            
            const orders = db.getOrdersByUser(currentUser.id);
            const ordersList = document.getElementById('ordersList');
            
            if (orders.length === 0) {
                ordersList.innerHTML = `
                    <div style="text-align: center; padding: 40px; color: #666;">
                        <p>暂无订单</p>
                    </div>
                `;
                return;
            }
            
            ordersList.innerHTML = orders.map(order => `
                <div class="order-card">
                    <div class="order-header">
                        <span class="order-id">订单号: #${order.id}</span>
                        <span class="order-status status-${order.status}">${getStatusText(order.status)}</span>
                    </div>
                    <div class="order-content">
                        <p><strong>商家:</strong> ${db.getMerchantById(order.merchantId)?.name || '未知商家'}</p>
                        <p><strong>菜品:</strong> ${order.dishes.map(dish => `${dish.name} x${dish.quantity}`).join(', ')}</p>
                        <p><strong>总价:</strong> ¥${order.finalPrice}</p>
                        <p><strong>下单时间:</strong> ${order.orderTime}</p>
                        <p><strong>配送地址:</strong> ${order.deliveryAddress}</p>
                        ${order.riderName ? `<p><strong>骑手:</strong> ${order.riderName}</p>` : ''}
                    </div>
                </div>
            `).join('');
        }
        
        function getStatusText(status) {
            const statusMap = {
                'pending': '待处理',
                'preparing': '制作中',
                'ready': '待配送',
                'delivering': '配送中',
                'completed': '已完成'
            };
            return statusMap[status] || status;
        }
        
        function viewMerchant(merchantId) {
            // 显示商家详情和菜品
            showMerchantDetails(merchantId);
        }
        
        function showMerchantDetails(merchantId) {
            const merchant = db.getMerchantById(merchantId);
            if (!merchant) {
                showMessage('商家信息不存在', 'error');
                return;
            }
            
            // 获取该商家的菜品
            const dishes = db.getDishesByMerchant(merchantId);
            
            // 创建商家详情模态框
            const modal = document.createElement('div');
            modal.style.cssText = `
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(0,0,0,0.5);
                z-index: 1000;
                display: flex;
                align-items: center;
                justify-content: center;
                padding: 20px;
            `;
            
            modal.innerHTML = `
                <div style="
                    background: white;
                    border-radius: 12px;
                    max-width: 800px;
                    width: 100%;
                    max-height: 90vh;
                    overflow-y: auto;
                    position: relative;
                ">
                    <div style="
                        position: sticky;
                        top: 0;
                        background: white;
                        padding: 20px;
                        border-bottom: 1px solid #eee;
                        display: flex;
                        justify-content: space-between;
                        align-items: center;
                    ">
                        <h2>${merchant.name}</h2>
                        <button onclick="this.closest('.merchant-modal').remove()" style="
                            background: #dc3545;
                            color: white;
                            border: none;
                            border-radius: 50%;
                            width: 30px;
                            height: 30px;
                            cursor: pointer;
                        ">×</button>
                    </div>
                    
                    <div style="padding: 20px;">
                        <div style="display: flex; gap: 20px; margin-bottom: 20px;">
                            <img src="${merchant.image}" alt="${merchant.name}" style="
                                width: 120px;
                                height: 120px;
                                border-radius: 8px;
                                object-fit: cover;
                            " onerror="this.src='https://via.placeholder.com/120x120?text=商家图片'">
                            <div style="flex: 1;">
                                <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 10px;">
                                    <span style="color: #ffc107;">⭐⭐⭐⭐⭐</span>
                                    <span style="color: #666;">${merchant.rating}</span>
                                </div>
                                <p style="color: #666; margin-bottom: 10px;">${merchant.description}</p>
                                <div style="display: flex; gap: 20px; color: #666; font-size: 14px;">
                                    <span>配送时间: ${merchant.deliveryTime}</span>
                                    <span>配送费: ¥${merchant.deliveryFee}</span>
                                    <span>起送价: ¥${merchant.minOrder}</span>
                                </div>
                            </div>
                        </div>
                        
                        <h3 style="margin-bottom: 15px;">菜品列表</h3>
                        <div id="merchantDishesGrid" style="
                            display: grid;
                            grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
                            gap: 15px;
                        ">
                            ${dishes.length === 0 ? 
                                '<div style="grid-column: 1 / -1; text-align: center; padding: 40px; color: #666;">该商家暂无菜品</div>' :
                                dishes.map(dish => `
                                    <div style="
                                        border: 1px solid #eee;
                                        border-radius: 8px;
                                        padding: 15px;
                                        transition: all 0.3s ease;
                                        cursor: pointer;
                                    " onmouseover="this.style.boxShadow='0 2px 10px rgba(0,0,0,0.1)'" onmouseout="this.style.boxShadow='none'">
                                        <img src="${dish.image}" alt="${dish.name}" style="
                                            width: 100%;
                                            height: 120px;
                                            border-radius: 6px;
                                            object-fit: cover;
                                            margin-bottom: 10px;
                                        " onerror="this.src='https://via.placeholder.com/250x120?text=菜品图片'">
                                        <h4 style="margin: 0 0 5px 0; color: #333;">${dish.name}</h4>
                                        <p style="color: #ff6b6b; font-weight: bold; margin: 0 0 5px 0;">¥${dish.price}</p>
                                        <p style="color: #666; font-size: 12px; margin: 0 0 10px 0;">${dish.description}</p>
                                        <div style="display: flex; justify-content: space-between; align-items: center;">
                                            <span style="background: #f8f9fa; color: #666; padding: 2px 6px; border-radius: 4px; font-size: 12px;">${dish.category}</span>
                                            <button onclick="addToCartFromMerchant(${dish.id})" style="
                                                background: #28a745;
                                                color: white;
                                                border: none;
                                                border-radius: 4px;
                                                padding: 5px 10px;
                                                cursor: pointer;
                                                font-size: 12px;
                                            ">加入购物车</button>
                                        </div>
                                    </div>
                                `).join('')
                            }
                        </div>
                    </div>
                </div>
            `;
            
            modal.className = 'merchant-modal';
            document.body.appendChild(modal);
            
            // 点击背景关闭模态框
            modal.addEventListener('click', (e) => {
                if (e.target === modal) {
                    modal.remove();
                }
            });
        }
        
        function addToCartFromMerchant(dishId) {
            addToCart(dishId);
            showMessage('已添加到购物车！', 'success');
        }
        
        // AI推荐相关函数
        async function refreshAIRecommendations() {
            showMessage('正在刷新AI推荐...', 'success');
            await loadDishes();
        }
        
        function showRecommendationSettings() {
            document.getElementById('recommendationSettingsModal').style.display = 'flex';
            loadRecommendationSettings();
        }
        
        function closeRecommendationSettings() {
            document.getElementById('recommendationSettingsModal').style.display = 'none';
        }
        
        function loadRecommendationSettings() {
            const settings = JSON.parse(localStorage.getItem('recommendationSettings') || '{}');
            
            document.getElementById('recommendationCount').value = settings.count || 10;
            document.getElementById('countValue').textContent = settings.count || 10;
            document.getElementById('prefSpicy').checked = settings.spicy || false;
            document.getElementById('prefSweet').checked = settings.sweet || false;
            document.getElementById('prefSour').checked = settings.sour || false;
            document.getElementById('prefHealthy').checked = settings.healthy || false;
            document.getElementById('priceMin').value = settings.priceMin || '';
            document.getElementById('priceMax').value = settings.priceMax || '';
            
            // 推荐数量滑块事件
            document.getElementById('recommendationCount').addEventListener('input', function() {
                document.getElementById('countValue').textContent = this.value;
            });
        }
        
        function saveRecommendationSettings() {
            const settings = {
                count: parseInt(document.getElementById('recommendationCount').value),
                spicy: document.getElementById('prefSpicy').checked,
                sweet: document.getElementById('prefSweet').checked,
                sour: document.getElementById('prefSour').checked,
                healthy: document.getElementById('prefHealthy').checked,
                priceMin: document.getElementById('priceMin').value,
                priceMax: document.getElementById('priceMax').value
            };
            
            localStorage.setItem('recommendationSettings', JSON.stringify(settings));
            showMessage('推荐设置已保存！', 'success');
            closeRecommendationSettings();
            
            // 重新生成推荐
            setTimeout(() => {
                refreshAIRecommendations();
            }, 500);
        }
        
        function resetRecommendationSettings() {
            document.getElementById('recommendationCount').value = 10;
            document.getElementById('countValue').textContent = '10';
            document.getElementById('prefSpicy').checked = false;
            document.getElementById('prefSweet').checked = false;
            document.getElementById('prefSour').checked = false;
            document.getElementById('prefHealthy').checked = false;
            document.getElementById('priceMin').value = '';
            document.getElementById('priceMax').value = '';
        }
        
        function showDishDetails(dishId) {
            const dish = db.getDishById(dishId);
            if (!dish) return;
            
            const modal = document.createElement('div');
            modal.style.cssText = `
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(0,0,0,0.5);
                z-index: 1000;
                display: flex;
                align-items: center;
                justify-content: center;
                padding: 20px;
            `;
            
            modal.innerHTML = `
                <div style="
                    background: white;
                    border-radius: 12px;
                    max-width: 600px;
                    width: 100%;
                    max-height: 80vh;
                    overflow-y: auto;
                    position: relative;
                ">
                    <div style="
                        position: sticky;
                        top: 0;
                        background: white;
                        padding: 20px;
                        border-bottom: 1px solid #eee;
                        display: flex;
                        justify-content: space-between;
                        align-items: center;
                    ">
                        <h3>${dish.name}</h3>
                        <button onclick="this.closest('.dish-detail-modal').remove()" style="
                            background: #dc3545;
                            color: white;
                            border: none;
                            border-radius: 50%;
                            width: 30px;
                            height: 30px;
                            cursor: pointer;
                        ">×</button>
                    </div>
                    <div style="padding: 20px;">
                        <div style="display: flex; gap: 20px; margin-bottom: 20px;">
                            <img src="${dish.image}" alt="${dish.name}" style="
                                width: 200px;
                                height: 200px;
                                border-radius: 8px;
                                object-fit: cover;
                            " onerror="this.src='https://via.placeholder.com/200x200?text=菜品图片'">
                            <div style="flex: 1;">
                                <h2 style="color: #333; margin-bottom: 10px;">${dish.name}</h2>
                                <div style="color: #ff6b6b; font-size: 24px; font-weight: bold; margin-bottom: 10px;">¥${dish.price}</div>
                                <div style="color: #666; margin-bottom: 10px;">${dish.category}</div>
                                <div style="color: #666; margin-bottom: 15px;">${dish.description}</div>
                                
                                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-bottom: 15px;">
                                    <div style="background: #f8f9fa; padding: 10px; border-radius: 6px; text-align: center;">
                                        <div style="font-weight: bold; color: #333;">评分</div>
                                        <div style="color: #ffc107;">${dish.rating} ⭐</div>
                                    </div>
                                    <div style="background: #f8f9fa; padding: 10px; border-radius: 6px; text-align: center;">
                                        <div style="font-weight: bold; color: #333;">销量</div>
                                        <div style="color: #28a745;">${dish.sales}</div>
                                    </div>
                                </div>
                                
                                <div style="background: #f8f9fa; padding: 15px; border-radius: 8px; margin-bottom: 15px;">
                                    <h4 style="margin-bottom: 10px; color: #333;">菜品详情</h4>
                                    <p style="margin: 5px 0; color: #666;"><strong>制作时间：</strong>${dish.cookingTime}分钟</p>
                                    <p style="margin: 5px 0; color: #666;"><strong>库存：</strong>${dish.stock}份</p>
                                    <p style="margin: 5px 0; color: #666;"><strong>食材：</strong>${dish.ingredients}</p>
                                    <p style="margin: 5px 0; color: #666;"><strong>过敏原：</strong>${dish.allergens}</p>
                                </div>
                                
                                <div style="display: flex; gap: 10px;">
                                    <button class="add-to-cart-btn" onclick="addToCart(${dish.id}); this.closest('.dish-detail-modal').remove();" style="flex: 1;">
                                        加入购物车
                                    </button>
                                    <button class="btn btn-secondary" onclick="this.closest('.dish-detail-modal').remove();" style="flex: 1;">
                                        关闭
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            `;
            
            modal.className = 'dish-detail-modal';
            document.body.appendChild(modal);
            
            // 点击背景关闭
            modal.addEventListener('click', (e) => {
                if (e.target === modal) {
                    modal.remove();
                }
            });
        }
        
        let cart = JSON.parse(localStorage.getItem('cart') || '[]');
        
        function addToCart(dishId) {
            const dish = db.getDishById(dishId);
            if (!dish) return;
            
            // 记录用户行为 - 点击菜品
            if (currentUser && window.aiRecommendationEngine) {
                aiRecommendationEngine.learnFromUserBehavior(currentUser.id, 'click', {
                    dishId: dishId,
                    context: {
                        time: new Date().toISOString(),
                        source: 'recommendation'
                    }
                });
            }
            
            const existingItem = cart.find(item => item.id === dishId);
            if (existingItem) {
                existingItem.quantity += 1;
            } else {
                cart.push({
                    id: dish.id,
                    name: dish.name,
                    price: dish.price,
                    image: dish.image,
                    quantity: 1,
                    merchantId: dish.merchantId
                });
            }
            
            localStorage.setItem('cart', JSON.stringify(cart));
            showMessage('已添加到购物车！', 'success');
            updateCartDisplay();
        }
        
        function updateCartDisplay() {
            const cartContent = document.getElementById('cartContent');
            if (!cartContent) return;
            
            if (cart.length === 0) {
                cartContent.innerHTML = `
                    <div style="text-align: center; padding: 40px; color: #666;">
                        <p>购物车是空的</p>
                        <p>去浏览商家添加喜欢的菜品吧！</p>
                    </div>
                `;
                return;
            }
            
            const total = cart.reduce((sum, item) => sum + (item.price * item.quantity), 0);
            
            cartContent.innerHTML = `
                <div class="cart-items">
                    ${cart.map(item => `
                        <div class="cart-item" style="display: flex; align-items: center; padding: 15px; border-bottom: 1px solid #eee;">
                            <img src="${item.image}" alt="${item.name}" style="width: 60px; height: 60px; border-radius: 8px; object-fit: cover; margin-right: 15px;">
                            <div style="flex: 1;">
                                <h4 style="margin: 0 0 5px 0;">${item.name}</h4>
                                <p style="color: #ff6b6b; font-weight: bold; margin: 0;">¥${item.price}</p>
                            </div>
                            <div style="display: flex; align-items: center; gap: 10px;">
                                <button onclick="updateQuantity(${item.id}, -1)" style="background: #f8f9fa; border: 1px solid #ddd; border-radius: 4px; width: 30px; height: 30px;">-</button>
                                <span style="min-width: 30px; text-align: center;">${item.quantity}</span>
                                <button onclick="updateQuantity(${item.id}, 1)" style="background: #f8f9fa; border: 1px solid #ddd; border-radius: 4px; width: 30px; height: 30px;">+</button>
                                <button onclick="removeFromCart(${item.id})" style="background: #dc3545; color: white; border: none; border-radius: 4px; padding: 5px 10px; margin-left: 10px;">删除</button>
                            </div>
                        </div>
                    `).join('')}
                </div>
                <div style="border-top: 2px solid #eee; padding: 20px 0; margin-top: 20px;">
                    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                        <h3>总计: ¥${total}</h3>
                    </div>
                    <button class="btn btn-primary" onclick="checkout()" style="width: 100%; padding: 15px; font-size: 16px;">立即结算</button>
                </div>
            `;
        }
        
        function updateQuantity(dishId, change) {
            const item = cart.find(item => item.id === dishId);
            if (item) {
                item.quantity += change;
                if (item.quantity <= 0) {
                    cart = cart.filter(item => item.id !== dishId);
                }
                localStorage.setItem('cart', JSON.stringify(cart));
                updateCartDisplay();
            }
        }
        
        function removeFromCart(dishId) {
            cart = cart.filter(item => item.id !== dishId);
            localStorage.setItem('cart', JSON.stringify(cart));
            updateCartDisplay();
            showMessage('已从购物车移除', 'success');
        }
        
        function checkout() {
            if (cart.length === 0) {
                showMessage('购物车是空的！', 'error');
                return;
            }
            
            const total = cart.reduce((sum, item) => sum + (item.price * item.quantity), 0);
            const deliveryFee = 5;
            const finalTotal = total + deliveryFee;
            
            // 创建订单
            const order = {
                userId: currentUser.id,
                merchantId: cart[0].merchantId,
                dishes: cart.map(item => ({
                    id: item.id,
                    name: item.name,
                    price: item.price,
                    quantity: item.quantity
                })),
                totalPrice: total,
                deliveryFee: deliveryFee,
                finalPrice: finalTotal,
                status: 'pending',
                riderStatus: 'available',
                orderTime: new Date().toLocaleString(),
                deliveryAddress: '北京市朝阳区xxx小区',
                customerPhone: currentUser.phone || '13800138000',
                customerName: currentUser.name || currentUser.username,
                notes: ''
            };
            
            // 记录用户行为 - 下单
            if (window.aiRecommendationEngine) {
                aiRecommendationEngine.learnFromUserBehavior(currentUser.id, 'order', {
                    dishes: order.dishes,
                    context: {
                        time: new Date().toISOString(),
                        totalPrice: order.finalPrice
                    }
                });
            }
            
            db.addOrder(order);
            
            // 清空购物车
            cart = [];
            localStorage.setItem('cart', JSON.stringify(cart));
            
            showMessage('订单提交成功！', 'success');
            updateCartDisplay();
            loadOrders();
        }
        
        function updateProfile() {
            const username = document.getElementById('profileUsername').value;
            const phone = document.getElementById('profilePhone').value;
            const email = document.getElementById('profileEmail').value;
            
            if (currentUser) {
                db.updateUser(currentUser.id, {
                    username: username,
                    phone: phone,
                    email: email
                });
                
                // 更新当前用户信息
                currentUser.username = username;
                currentUser.phone = phone;
                currentUser.email = email;
                localStorage.setItem('currentUser', JSON.stringify(currentUser));
                
                showMessage('个人信息更新成功！', 'success');
            }
        }
        
        function addAddress() {
            const address = prompt('请输入新地址：');
            if (address && currentUser) {
                if (!currentUser.addresses) {
                    currentUser.addresses = [];
                }
                currentUser.addresses.push({
                    id: Date.now(),
                    address: address,
                    isDefault: currentUser.addresses.length === 0
                });
                
                db.updateUser(currentUser.id, { addresses: currentUser.addresses });
                localStorage.setItem('currentUser', JSON.stringify(currentUser));
                loadAddresses();
                showMessage('地址添加成功！', 'success');
            }
        }
        
        function loadAddresses() {
            const addressList = document.getElementById('addressList');
            if (!addressList || !currentUser) return;
            
            const addresses = currentUser.addresses || [];
            
            if (addresses.length === 0) {
                addressList.innerHTML = '<p style="color: #666;">暂无收货地址</p>';
                return;
            }
            
            addressList.innerHTML = addresses.map(addr => `
                <div style="border: 1px solid #eee; border-radius: 8px; padding: 15px; margin-bottom: 10px;">
                    <div style="display: flex; justify-content: space-between; align-items: center;">
                        <div>
                            <p style="margin: 0; font-weight: 600;">${addr.address}</p>
                            ${addr.isDefault ? '<span style="background: #ff6b6b; color: white; padding: 2px 8px; border-radius: 12px; font-size: 12px;">默认</span>' : ''}
                        </div>
                        <div>
                            <button onclick="setDefaultAddress(${addr.id})" style="background: #28a745; color: white; border: none; border-radius: 4px; padding: 5px 10px; margin-right: 5px;">设为默认</button>
                            <button onclick="deleteAddress(${addr.id})" style="background: #dc3545; color: white; border: none; border-radius: 4px; padding: 5px 10px;">删除</button>
                        </div>
                    </div>
                </div>
            `).join('');
        }
        
        function setDefaultAddress(addressId) {
            if (currentUser && currentUser.addresses) {
                currentUser.addresses.forEach(addr => {
                    addr.isDefault = addr.id === addressId;
                });
                
                db.updateUser(currentUser.id, { addresses: currentUser.addresses });
                localStorage.setItem('currentUser', JSON.stringify(currentUser));
                loadAddresses();
                showMessage('默认地址设置成功！', 'success');
            }
        }
        
        function deleteAddress(addressId) {
            if (confirm('确定要删除这个地址吗？')) {
                if (currentUser && currentUser.addresses) {
                    currentUser.addresses = currentUser.addresses.filter(addr => addr.id !== addressId);
                    
                    db.updateUser(currentUser.id, { addresses: currentUser.addresses });
                    localStorage.setItem('currentUser', JSON.stringify(currentUser));
                    loadAddresses();
                    showMessage('地址删除成功！', 'success');
                }
            }
        }
        
        function showMessage(text, type) {
            const messageDiv = document.getElementById('message');
            messageDiv.innerHTML = `<div class="message ${type}">${text}</div>`;
            setTimeout(() => {
                messageDiv.innerHTML = '';
            }, 3000);
        }
        
        function logout() {
            localStorage.removeItem('currentUser');
            window.location.href = 'home.html';
        }
        
        function goBack() {
            window.location.href = 'home.html';
        }
    </script>
</body>
</html>
